<template>
  <base-modal :title="dialogData[dialogType].title" :show.sync="visible" width="500px" class="batch-editing-customer-dialog">
    <!-- modal content -->
    <div class="add-menu-dialog-box">
      <!-- 新建一级分类、添加子集类型、重命名子集类型 -->
      <template v-if="dialogType == 'addMenu' || dialogType == 'addMenuChild' || dialogType == 'renameMenuChild'">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" class="demo-ruleForm" label-position="top" status-icon>
          <el-form-item :label="$t('product.productType.publicDialog.text3')" prop="name">
            <el-input v-model="ruleForm.name" maxlength="30"></el-input>
          </el-form-item>
        </el-form>
      </template>

      <!-- 其他：关联备件、关联知识库、关联产品 -->
      <template v-else>
        <div class="flex-x copy-el-form-item">
          <div class="lable-100">
            {{ $t('common.placeholder.select') }}：
          </div>
          <el-select 
            v-model="nowChooseArr" 
            multiple 
            filterable 
            remote 
            collapse-tags 
            clearable 
            :multiple-limit="0" 
            v-el-select-loadmore="loadMoreOptions"
            :placeholder="$t('common.placeholder.select')" 
            :remote-method="remoteSelectSearch" 
            :loading="selectLoading" 
            class="flex-1 pos-r" 
            popper-class="max-w-488" 
            :class="dialogType === 'linkWiki' || dialogType == 'linkPart' ? 'select-list' : ''"
            @focus="focus" 
            @change="checkProduct" 
          >
            <el-option 
              v-for="item in dialogData[dialogType] && dialogData[dialogType].options"
              :key="item.id" 
              :label="dialogType == 'linkWiki' ? item.title : item.name" :value="item.id"
            >
              <div class="flex-x overHideCon-1">
                <!-- 关联备件 -->
                <template v-if="dialogType == 'linkPart'">
                  <ul class="common-list part-list">
                    <li class="common-list-name">{{ item.name }}</li>
                    <li>{{ $t('common.fields.serialNumber.displayName') }}：{{ item.serialNumber }}</li>
                    <li>{{ $t('common.part.specifications') }}：{{ item.standard }}</li>
                  </ul>
                </template>

                <!-- 关联知识库 -->
                <template v-if="dialogType == 'linkWiki'">
                  <div class="common-list wiki-item">
                    <h3 class="common-list-name">{{ item.title }}</h3>
                    <template v-if="isOpenData && item.createUserStaffId">
                      <p>
                        <i18n>
                          <open-data type="userName" :openid="item.createUserStaffId"></open-data>
                        </i18n>
                        {{ $t('product.productType.publicDialog.text1', { createTime: item.createTime, type: item.type }) }}
                      </p>
                    </template>
                    <template v-else>
                      <p>{{ item.createUserName }} {{ $t('product.productType.publicDialog.text1', { createTime: item.createTime, type: item.type }) }}</p>
                    </template>
                    <p class="wiki-content" v-html="item.content"></p>
                    <p v-if="item.label && item.label.length">
                      <i class="iconfont icon-tag"></i>
                      <span v-for="label in item.label" :key="label">{{ label }}</span>
                    </p>
                  </div>
                </template>
                
                <!-- 关联产品 -->
                <template v-if="dialogType == 'linkProduct'">
                  <div class="link-product">
                    <ul class="common-list">
                      <li class="common-list-name product-name">{{ item.name }}</li>
                      <li>{{ $t('common.fields.productNo.displayName') }}：{{ item.serialNumber }}</li>
                      <li>{{ $t('common.base.productType') }}：{{ item.catalog.catalogName }}</li>
                      <li v-if="showLinkman">{{ $t('common.base.contact') }}：{{ item.linkman.name }}</li>
                      <li v-if="showAddress">{{ $t('common.form.type.productCompleteAddress') }}：{{item.address | fmt_address }}</li>
                      <li v-if="item.customer && item.customer.id">{{ $t('common.base.customer') }}：{{ item.customer.name }}</li>
                      <li v-else>
                        {{ $t('common.base.customer') }}：<span class="customer-unbind-name">{{ $t('common.base.notContact') }}</span>
                      </li>
                    </ul>
                  </div>
                </template>
              </div>
            </el-option>
          </el-select>
        </div>
      </template>
    </div>

    <!-- modal footer -->
    <div slot="footer">
      <el-button @click="visible = false">{{ $t('common.base.cancel') }}</el-button>
      <el-button type="primary" :loading="btnLoading" @click="confirm">{{ $t('common.base.confirm') }}</el-button>
    </div>
  </base-modal>
</template>

<script>
import { isOpenData } from '@src/util/platform';
import { getPagePart, getPageWiki, cloneData, productList } from '@src/api/ProductV2Api';
import { debounce } from 'lodash';
import { Cascader } from 'element-ui';
import { objectDateToTimestamp } from 'pub-bbx-utils';

export default {
	name: 'public-dialog',
	props: {
		visibleProp: {
			type: Boolean,
		},
		dialogType: {
			type: String,
			default: 'addMenu',
		},
		nowEditMenu: {
			type: Object,
		},
		childData: {
			type: Object,
		},
		showLinkman: {
			type: Boolean,
			default: false,
		},
		showAddress: {
			type: Boolean,
			default: false,
		},
	},
	data() {
		return {
			isOpenData,
			searchPaarms: {
				keyWord: '',
				pageSize: 5,
				pageNum: 1,
			},
			selectHasNextPage: true,
			loadMoreOptions: {
        disabled: false,
        callback: this.remoteSelectSearchMore,
        distance: 10,
      },
			dialogData: {
				addMenu: {
					title: this.$t('product.productType.publicDialog.text4'),
				},
				addMenuChild: {
					title: this.$t('product.productType.publicDialog.text4'),
				},
				linkProduct: {
					title: this.$t('common.fields.relationProduct.displayName'),
					http: productList,
					options: [],
				},
				renameMenuChild: {
					title: this.$t('common.base.rename'),
				},
				linkPart: {
					title: this.$t('common.form.preview.relatedProduct.label4'),
					http: getPagePart,
					options: [],
				},
				linkWiki: {
					title: this.$t('common.form.preview.relatedProduct.label5'),
					http: getPageWiki,
					options: [],
				},
			},
			nowChooseArr: [],
			selectedSparepart: [],
			ruleForm: {
				name: '',
			},
			rules: {
				name: [
					{ required: true, message: this.$t('product.productType.publicDialog.text6'), trigger: 'blur' },
					{ min: 1, max: 30, message: this.$t('common.base.tip.maxCharacterTip', { num: '30' }), trigger: 'change' },
				],
			},
			selectLoading: false,
			btnLoading: false,

			catalog: [],
			catalogTree: [],
			checkIdList: [],
			checkProductList: [],
		};
	},
	computed: {
		visible: {
			get() {
				return this.visibleProp;
			},
			set(val) {
				this.$emit('changeVisibleProp', val);
			},
		},
	},
	watch: {
		visible(newVal, oldVal) {
			this.searchPaarms = {
				keyWord: '',
				pageSize: 5,
				pageNum: 1,
			}
			this.selectHasNextPage = true;
			if (newVal == false) {
				if (this.dialogType == 'addMenu' || this.dialogType == 'renameMenuChild' || this.dialogType == 'addMenuChild') this.$refs['ruleForm'].resetFields();
				this.nowChooseArr = [];
				this.btnLoading = false;
				this.checkIdList = [];
				if (this.checkProductList.length) {
					this.checkProductList.forEach(item => (item.checked = false));
				}
				this.checkProductList = [];
			} else {
				this.$nextTick(() => {
					if (this.dialogType == 'renameMenuChild') this.$set(this.ruleForm, 'name', this.childData.name);
				});
			}
		},
	},
	methods: {
		// 选择产品
		checkProduct(val) {
			this.checkProductList.forEach(item => (item.checked = false));
			this.checkIdList = val;
			this.checkProductList = [];
			const options = this.dialogData[this.dialogType].options;
			val.forEach(item => {
				const p = options.find(o => o.id === item);
				p.checked = true;
				this.checkProductList.push(p);
			});
		},
		// 获取复制产品类型的树
		async cloneData() {
			try {
				let { code, result } = await cloneData();
				if (code === 0) {
					this.deleteNoChildren(result);
					this.catalogTree = result;
				}
			} catch (err) {
				console.error(err);
			}
		},
		// 树的子集如果没有内容，则删除tasks
		deleteNoChildren(list) {
			list.forEach(item => {
				if (item.tasks.length === 0) {
					delete item.tasks;
				} else {
					this.deleteNoChildren(item.tasks);
				}
			});
		},
		confirm() {
			if (this.dialogType == 'addMenu' || this.dialogType == 'addMenuChild' || this.dialogType == 'renameMenuChild') {
				this.$refs['ruleForm'].validate(valid => {
					if (valid) this.$emit('confirm', { catalogName: this.ruleForm.name });
				});
			} else if (this.dialogType == 'linkPart' || this.dialogType == 'linkWiki') {
				if (!this.nowChooseArr.length) {
					return this.$message.error(this.$t('product.component.publicDialog.tip2'));
				}
				this.$emit('confirm', { nowChooseArr: this.nowChooseArr });
			} else if (this.dialogType == 'linkProduct') {
				if (!this.nowChooseArr.length) {
					return this.$message.error(this.$t('product.productType.publicDialog.text7'));
				}
				const alreadyRelationed = this.checkProductList.find(item => item.catalogId);
				if (alreadyRelationed) {
					this.$confirm(this.$t('product.productType.publicDialog.text8'), this.$t('product.productType.publicDialog.text9'), {
						confirmButtonText: this.$t('common.base.makeSure'),
						cancelButtonText: this.$t('common.base.cancel'),
						customClass: 'checkProductConfirm',
						type: 'warning',
					})
						.then(() => {
							this.$emit('confirm', { nowChooseArr: this.nowChooseArr });
						})
						.catch(() => {});
				} else {
					this.$emit('confirm', { nowChooseArr: this.nowChooseArr });
				}
			}
		},
		dataUpdate(e, key) {
			this[key] = e;
		},
		calculateClass(e, t) {
			let str = '';
			if (e.slotNowData) {
				for (let index = 0; index < e.slotNowData.length; index++) {
					const element = e.slotNowData[index];
					if (element.orderId === t.orderId) {
						str = 'checked-item';
					}
				}
			}
			return str;
		},
		slotClick(e, ref) {
			this.$refs[ref].chooseItem(e);
		},
		focus() {
			if (!this.dialogData[this.dialogType].options.length) this.remoteSelectSearch('', true);
		},
		remoteSelectSearchMore() {
			if(this.dialogType !== 'linkPart' || !this.selectHasNextPage) return;
			this.remoteSelectSearch(this.searchPaarms.keyWord, true, true);
		},
		remoteSelectSearch: debounce(function (e, type, loadMore) {
			if (!type && !e && this.dialogType !== 'linkPart') {
				return;
			}
			this.searchPaarms.keyWord = e;
			if(loadMore) {
				this.searchPaarms.pageNum += 1 
			} else {
				this.searchPaarms.pageNum = 1
			}
			this.selectLoading = true;
			this.dialogData[this.dialogType]
				.http(this.searchPaarms)
				.then(res => {
					if (!res) {
						this.selectHasNextPage = false;
						return;
					}
					if (this.dialogType === 'linkProduct') {
						res.result.content.forEach(item => (item.checked = false));
						let content = res.result.content || [];
						content = content.filter(item => !this.checkProductList.find(c => c.id === item.id));
						this.dialogData[this.dialogType].options = [...this.checkProductList, ...content];
					} else {
						let list = res.result.list || [];
						this.selectHasNextPage = res.result.hasNextPage
						if (loadMore) {
							Array.prototype.push.apply(this.dialogData[this.dialogType].options, list)
						} else {
							this.dialogData[this.dialogType].options = list;
						}
					}
				})
				.catch(err => {})
				.finally(() => {
					this.selectLoading = false;
				});
		}, 800),
    
    /**
     * @description: 搜索备件
     * @param {Object} params { keyword, pageSize, pageNum }
     * @return {Object} res
     */    
		searchPart(params) {
			const pms = params || {};
			pms.repertoryId = this.repertoryId || '';
			pms.with_OOS = false;
			pms.keyWord = pms.keyword;
			objectDateToTimestamp(pms, ['timeEnd', 'timeStart'])
			return this.$http
				.post('/task/spare/list', pms)
				.then(res => {
					if (!res || !res.list) return;
					res.list = res.list.map(template =>
						Object.freeze({
							label: template.name,
							value: template.id,
							...template,
						})
					);
					return res;
				})
				.catch(e => console.error(e));
		},
		/**
		 * @description 选择备件
		 */
		updatePart(value) {
			let newValue = value[0];

			for (let key in this.sparepart) {
				if (key == 'salePrice') {
					this.sparepart.salePrice = newValue.salePrice.toFixed(2);
				} else if (key == 'number') {
					this.sparepart.number = newValue.availableNum > 1 ? 1 : newValue.availableNum;
				} else {
					this.sparepart[key] = newValue[key];
				}
			}
		},
		changeBtnLoading(e) {
			this.btnLoading = e;
		},
	},
	components: {
		[Cascader.name]: Cascader,
	},
};
</script>
<style lang="scss" scoped>
.add-menu-dialog-box {
	padding: 12px 12px 0 0;
}
.lable-100 {
	width: 70px;
}
.copy-el-form-item {
	margin-bottom: 18px;
}
.checked-item {
	background: $color-primary;
}
.link-product {
	display: flex;
	padding: 5px;
	// border-bottom: 1px solid $color-border-l1;
	width: 100%;
	::v-deep .el-checkbox {
		margin-right: 5px;
	}
	ul {
		padding-left: 5px;
		.product-name {
			font-size: 14px;
			color: $text-color-primary;
		}
		li {
			font-size: 12px;
			height: 22px;
			line-height: 22px;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
			color: $text-color-secondary;
		}
	}
}
.common-list {
	font-size: 12px;
	.common-list-name {
		font-size: 14px;
		font-weight: bold;
		color: #606266;
	}
	.common-list > * {
		color: #8c8c8c;
	}
	.customer-unbind-name {
		color: #bfbfbf;
	}
}
.theme-default .el-option {
	&.selected {
		background: #fff;
		.common-list > * {
			font-weight: bold;
			color: #666;
		}
		.common-list-name {
			color: $color-primary-light-6;
		}
		&:hover {
			background-color: $color-primary-light-1;
		}
	}
}
</style>
<style lang="scss">
.el-dialog__body {
	border-top: 1px solid rgba(0, 0, 0, 0.09);
	border-bottom: 1px solid rgba(0, 0, 0, 0.09);
	padding: 0;
}

.el-select__input {
	margin-left: 12px;
}

.el-select-dropdown__item {
	height: auto;
	width: 360px;
}

.select-list {
	width: calc(100% - 100px);
}
.part-list {
	width: 100%;
	padding-left: 0;
	// border-bottom: 1px solid $color-border-l3;
	padding: 5px 0;
	overflow: auto;
	li {
		height: 20px;
		line-height: 20px;
	}
}

.el-select-dropdown.is-multiple .el-select-dropdown__item.selected {
	p {
		color: $color-primary;
	}
	li {
		color: $color-primary;
	}
}

.wiki-item {
	padding: 5px 0;
	width: 100%;
	// border-bottom: 1px solid $color-border-l3;
	overflow: auto;
	h4 {
		margin-bottom: 0;
		height: 20px;
		line-height: 20px;
	}
	p {
		margin-bottom: 0;
		height: 20px;
		line-height: 20px;
		color: $text-color-secondary;
		font-size: 12px;

		span {
			padding: 2px 5px;
			margin-right: 6px;
			background-color: $bg-color-l3;
		}
	}
	.wiki-content {
		white-space: nowrap;
		text-overflow: ellipsis;
		overflow: hidden;
		word-break: break-all;
	}
}

.el-select__tags-text {
	display: -webkit-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 1;
	overflow: hidden;
	white-space: normal;
	word-wrap: break-word;
	word-break: break-all;
}
.el-select .el-tag {
	position: relative;
	display: flex;
	align-items: center;
	max-width: 60%;
}
.el-select .el-select__tags-text {
	flex: 1;
}
.batch-editing-customer-dialog {
	.base-modal-body {
		padding: 10px 30px 0;
	}

	.form-name,
	.form-item label {
		width: 70px;
		padding: 0;
		line-height: 32px;
	}

	.el-select {
		width: 100%;
	}

	.item {
		display: flex;
		justify-content: space-between;
		line-height: 32px;
		div {
			flex-grow: 1;
			.el-select {
				width: 100%;
			}
		}
	}

	.dialog-footer {
		display: flex;
		justify-content: flex-end;
	}
}
.tips-prev {
	color: #8c8c8c;
}
</style>

<style lang="scss">
.el-select-dropdown__empty {
	display: block !important;
}
.checkProductConfirm {
	vertical-align: baseline;
}
</style>
